import socket
import json
import base64
import numpy as np
import time
import random

def base64_encode_image(image_path):
    with open(image_path, "rb") as image_file:
        # 读取文件内容
        image_data = image_file.read()
        # 将文件内容转换为Base64编码
        base64_encoded_data = base64.b64encode(image_data)
        # 将Base64编码的二进制数据转换为ASCII文本
        base64_message = base64_encoded_data.decode('utf-8')
        return base64_message

def generate_sample_data():
    # 生成随机的星座图数据
    real_part = np.random.uniform(-3, 3, 100).tolist()
    imag_part = np.random.uniform(-3, 3, 100).tolist()

    # 生成一些示例的信号质量参数
    snr = np.random.uniform(15, 25)
    bler = np.random.uniform(0, 0.1)
    ber = np.random.uniform(0, 0.01)

    # 生成示例的图片数据（这里仅为了演示，实际中应替换为实际图片数据）
    img_data = base64_encode_image('favicon.ico')

    return {
        "real_part": real_part,
        "imag_part": imag_part,
        "SNR": snr,
        "BLER": bler,
        "BER": ber,
        "PICTURE": img_data,
        "STA": random.randint(0, 5),
    }

def udp_server():
    server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server.bind(("127.0.0.1", 8000))
    print("Server listening on 127.0.0.1:8000")

    while True:
        data, addr = server.recvfrom(4096)
        request = data.decode("utf-8")
        print(f"Received: {request}")

        if "USRPCONNECT" in request:
            # 解析 JSON 数据并处理 USRP 配置
            try:
                json_data = json.loads(request.split("\r\n\r\n", 1)[1])
                print("USRP Config:", json_data)
            except json.JSONDecodeError:
                print("Error decoding JSON")

            # 假设配置成功
            response = "USRPCONNECT 200\r\n\r\n"
            server.sendto(response.encode("utf-8"), addr)

        elif "SINGLEREQ" in request:
            sample_data = generate_sample_data()
            response_data = f"SINGLEREQ 200\r\n\n\n\n{json.dumps(sample_data)}"
            server.sendto(response_data.encode("utf-8"), addr)
        elif "CONTINUOUSREQ" in request:
            print("Continuous request received")
            counts = 0
            while counts <= 1500:
                counts += 1
                sample_data = generate_sample_data()
                response_data = f"CONTINUOUSREQ2 200\r\n\n\n\n{json.dumps(sample_data)}"
                server.sendto(response_data.encode("utf-8"), addr)
                time.sleep(0.1)  # 每秒发送一次数据
        elif "CONTINUOUSREQ" in request:
            print("Continuous request received")
            counts = 0
            while counts <= 15:
                counts += 1
                sample_data = generate_sample_data()
                response_data = f"CONTINUOUSREQ 200\r\n\n\n\n{json.dumps(sample_data)}"
                server.sendto(response_data.encode("utf-8"), addr)
                time.sleep(0.1)  # 每秒发送一次数据

        else:
            response = "Unknown command\r\n\r\n\r\n"
            server.sendto(response.encode("utf-8"), addr)

if __name__ == "__main__":
    udp_server()
